<?php
namespace User\Controller;
use Think\Controller;
/**
 * 员工自助信息修改控制器 InfoController.class.php
 */
class InfoController extends CommonController{
    /* 属性声明 */
    private $main_conf_file = null;
    //扩展配置文件
    private $kz_conf_file = "./Org/Data/kz_conf.json";
    //时间验证字段配置文件
    private $sj_conf_file = "./Org/Data/sj_zd_conf.json";
    /* 方法声明 */
    /**
     * 构造方法
     */
    public function __construct() {
        parent::__construct();
        //检测用户合法性
        if(!$this -> uuid = session('uuid')){
            $this -> error('获取员工标识失败!');
        }
        $this -> corpid = session('corpid');
        $this -> main_conf_file = "./Org/Data/UserData/main_conf/{$this->corpid}_main.conf";

        //获取成员数据
        $this -> redis -> select(10);
        $this -> info = json_decode($this -> redis -> hget('user_list',$this->uuid),true);
        $this -> sub_list = $this -> info['information'];
    }
    
    /**
     * 修改个人信息
     */
    public function edit(){
        $data = I('post.');
        //dump($data);exit;

        //设置时间限制
        set_time_limit(0);

        //检测是否是员工基本信息
        if($data['table_name']=='BO_CASC_HR_YGRS'){
            $this -> updateBaseInfo($data);
        }else{
            $this -> updateSubItem($data,$data['table_name']);
        }
    }
    
    /**
     * 修改员工基本信息
     * @param array $data post上传数据
     * @return void
     */
    private function updateBaseInfo($data){
        //获取当前子集数据
        $userinfo = $this->sub_list;
        $temp_data = $userinfo[$data['table_name']]['sublist'];
        $change_type = $userinfo[$data['table_name']]['change_type'];
        //dump($temp_data);exit;

        //上传附件
        $file = $_FILES;
        foreach($_FILES as $k=>$v){
            $tob = 0;
            foreach($v['name'] as $k1=>$v1){
                if($v1){
                    $tob++;
                }
            }
            if($tob){
                $this->upload($k,$data['table_name'],0);
                $_FILES = $file;
                if($k != 'ZP'){
                    $temp_data[$k]['change_type'] = 1;
                    $change_type = 1;
                }

            }
        }

        //修改数据
        foreach($temp_data as $k =>$v){
            if(array_key_exists($k,$data)){
                $lao_value = $v['value'];
                //判断如果是时间类型把提交的时间拼接' 00:00:00.0'
                if($v['type'] == 'DATE' && $data[$k] != ''){
                    $data[$k] = $data[$k].' 00:00:00.0';
                }
                //判断有没有提交新值ba,把有修改的字段和当前子集的修改状设为1
                if( $lao_value != $data[$k]){
                    //情况1:value oldvalue 两者全无值状态
                    if(($v['value']=='') && ($v['oldvalue']=='')){
                        $temp_data[$k]['value'] = $data[$k];
                    }elseif(($v['value']!='') && ($v['oldvalue']=='')){
                        //情况2:有值状态 oldvalue为空
                        $temp_data[$k]['oldvalue'] = $v['value'];
                        $temp_data[$k]['value'] = $data[$k];
                    }elseif(($v['value']!='')&&($v['oldvalue']!='')){
                        //情况3:有值状态 oldvalue不为空
                        //处理方式:如果当前字段没有修改,old=val,init=old, 有修改,old不做处理
                        if($v['change_type'] == 0){
                            $temp_data[$k]['oldvalue'] = $v['value'];
                            $temp_data[$k]['initvalue'] = $v['oldvalue'];
                        }
                        $temp_data[$k]['value'] = $data[$k];
                    }elseif(($v['value']=='') && ($v['oldvalue']!='')){
                        //情况4:无值状态 oldvalue不为空
                        $temp_data[$k]['value'] = $data[$k];
                    }
                    $temp_data[$k]['change_type'] = 1;
                    $change_type = 1;
                }
            }
        }
        //dump($temp_data);exit;
        //回填数据
        $info = $this -> info;
        $info['information'][$data['table_name']]['sublist'] = $temp_data;
        $info['information'][$data['table_name']]['change_type'] = $change_type;
        //删除审批标识
        unset($info['information'][$data['table_name']]['sp_type']);
        unset($info['information'][$data['table_name']]['reason']);
        //dump( $info['information'][$data['table_name']]);exit;
        $info = json_encode($info);
        //回写数据
        $this -> redis -> select(10);
        $this -> redis -> hset('user_list',$this->uuid,$info);
        $this -> success('修改成功!');
    }
    
    /**
     * 修改员工子集信息
     */
    private function updateSubItem($data,$table_name){
        //获取当前子集数据
        $userinfo = $this->sub_list;
        $temp_data = $userinfo[$table_name];
        //dump($temp_data);exit;

        //1.获取唯一性字段
        $wyx_info = [];
        foreach($temp_data['sublist'] as $k=>$v){
            if($v['wyx'] == true){
                $wyx_info[] = $k;
            }
        }
        //dump($wyx_info);exit;
        //无值状态
        //dump($_FILES);exit;
        if($data['has_value']==0){
            //上传附件
            $file = $_FILES;
            foreach($_FILES as $k=>$v){
                $tob = 0;
                foreach($v['name'] as $k1=>$v1){
                    if($v1){
                        $tob++;
                    }
                }
                if($tob){
                    $this->upload($k,$data['table_name'],0);
                    $_FILES = $file;
                }
            }

            //初始化数据//生成新值
            $new_data = $this -> createNewData($data,$temp_data['sublist']);
            $info = $this -> info;
            $info['information'][$table_name]['subvalue'][0]['awsid'] = '';
            $info['information'][$table_name]['subvalue'][0]['info'] = $new_data;
            $info['information'][$table_name]['subvalue'][0]['change_type'] = 1;
            $info['information'][$table_name]['status']['insert'][] = 0;
            $info['information'][$table_name]['change_type'] = 1;
            //回写数据
            $info = json_encode($info);
            $this -> redis -> select(10);
            $this -> redis -> hset('user_list',$this->uuid,$info);
            $this -> success('编辑成功!');
        }else{
            //有值状态
            //获取数据坐标
            $_offset_id = $data['_offset_id'];
            //获取指定值集合数据
            $temp_data_info = $temp_data['subvalue'][$_offset_id]['info'];
            //dump($temp_data_info);exit;
            $type = 0;

            //上传附件
            $file = $_FILES;
            foreach($_FILES as $k=>$v){
                $tob = 0;
                foreach($v['name'] as $k1=>$v1){
                    if($v1){
                        $tob++;
                    }
                }
                if($tob){
                    $this->upload($k,$data['table_name'],$_offset_id);
                    $_FILES = $file;

                    $temp_data_info[$k]['change_type'] = 1;
                    $type = 1;
                }
            }

            foreach($temp_data_info as $k => $v){
                if(array_key_exists($k,$data)){
                    $lao_value = $v['value'];
                    //判断如果是时间类型把提交的时间拼接' 00:00:00.0'
                    if($v['type'] == 'DATE' && $data[$k] != ''){
                        $data[$k] = $data[$k].' 00:00:00.0';
                    }

                    //判断值有修改,把修改的列放进update里,把有修改的字段和当前子集的修改状设为1
                    if($lao_value != $data[$k]){
                        //情况1:value oldvalue 两者全无值状态
                        if(($v['value']=='') && ($v['oldvalue']=='')){
                            $temp_data_info[$k]['value'] = $data[$k];
                        }elseif(($v['value']!='') && ($v['oldvalue']=='')){
                            //情况2:有值状态 oldvalue为空
                            $temp_data_info[$k]['oldvalue'] = $v['value'];
                            $temp_data_info[$k]['value'] = $data[$k];
                        }elseif(($v['value']!='') && ($v['oldvalue']!='')){
                            //情况3:有值状态 oldvalue不为空
                            //处理方式:如果当前字段没有修改,old=val,init=old, 有修改,old不做处理
                            if($v['change_type'] == 0){
                                $temp_data_info[$k]['oldvalue'] = $v['value'];
                                $temp_data_info[$k]['initvalue'] = $v['oldvalue'];
                            }
                            $temp_data_info[$k]['value'] = $data[$k];
                        }elseif(($v['value']=='') && ($v['oldvalue']!='')){
                            //情况4:无值状态 oldvalue不为空
                            $temp_data_info[$k]['value'] = $data[$k];
                        }

                        $temp_data_info[$k]['change_type'] = 1;  //当前字段修改状态为1
                        $type = 1;  //修改状态
                    }
                }
            }
            if($type == 1){
                $temp_data['subvalue'][$_offset_id]['change_type'] = 1; //当前条修改状态为1
                $temp_data['change_type'] = 1;  //当前子集修改状态为1
                //提交修改 去除审批标识
                unset($temp_data['subvalue'][$_offset_id]['sp_type']);
                unset($temp_data['subvalue'][$_offset_id]['reason']);

            }

            //检测是否为新建数据
            $status = $temp_data['status'];
            if(!in_array($_offset_id,$status['insert'])){
                if($type == 1){
                    //索引为已有数据
                    $status['update'][] = $_offset_id;
                    //去重处理
                    $status['update'] = array_unique($status['update']);
                    //判断此数据在不在delete里,在就去除
                    $awsid = $temp_data['subvalue'][$_offset_id]['awsid'];
                    if(in_array($awsid,$status['delete'])){
                        unset($status['delete'][$_offset_id]);
                    }
                }
            }

            //整理唯一性字段数据
            if($wyx_info){
                foreach($wyx_info as $k=>$v){
                    if($data[$v] == '是'){
                        if(isset($data['upd-'.$v])){
                            $val = $data['upd-'.$v];
                            $temp_data['subvalue'][$val]['info'][$v]['oldvalue'] = $temp_data['subvalue'][$val]['info'][$v]['value'];
                            $temp_data['subvalue'][$val]['info'][$v]['value'] = '否';
                            $temp_data['subvalue'][$val]['info'][$v]['change_type'] = 1;
                            $temp_data['subvalue'][$val]['change_type'] = 1;
                            if(!in_array($val,$status['insert'])){
                                //索引为已有数据
                                $status['update'][] = $val;
                                //去重处理
                                $status['update'] = array_unique($status['update']);
                            }
                        }

                    }
                }
            }
            //回填数据
            $temp_data['subvalue'][$_offset_id]['info'] = $temp_data_info;
            //dump($temp_data);exit;
            $info = $this -> info;
            $info['information'][$table_name] = $temp_data;
            $info['information'][$table_name]['status'] = $status;
            //dump($info['information'][$table_name]);exit;
            $info = json_encode($info);
            //回写数据
            $this -> redis -> select(10);
            $this -> redis -> hset('user_list',$this->uuid,$info);
            $this -> success('修改成功!');
        }
    }


    //上传附件方法
    private function  upload($filename,$menu,$offset){
        $arr = [];
        foreach ($_FILES[$filename]['name'] as $k => $v) {
            $arr[] = array(
                'name' => $v,
                'type' => $_FILES[$filename]['type'][$k],
                'tmp_name' => $_FILES[$filename]['tmp_name'][$k],
                'error' => $_FILES[$filename]['error'][$k],
                'size' => $_FILES[$filename]['size'][$k],
            );
        }
        $_FILES = $arr; //把循环后的上传数据赋给$_FILES,因为上传类要在$_FILES里获取数据
        //dump($arr);exit;
        $viewpath = C('IMAGE_CONFIG')['VIEWPATH'];
        foreach($arr as $k=>$v){
            if($v['error'] == 0){
                $rst = uploadfile($k,$this->uuid,$menu);
                if($rst['type'] === 0){
                    $this->error($rst['error']);
                    exit;
                }else{
                    $this->redis->select(9);
                    $file_info = unserialize($this->redis->hget('file_'.$this->uuid,$menu));
                    //dump($file_info);exit;
                    //如果是照片
                    if($filename == 'ZP'){
                        $file_info[$offset][$filename] = [
                            $rst[$k]['name'] => [
                                'href' => $viewpath . $rst[$k]['savepath'] . $rst[$k]['savename'],
                                'status' => 2
                            ]
                        ];
                    }else {
                        //附件
                        if (array_key_exists($v['name'], $file_info[$offset][$filename])) {
                            if ($file_info[$offset][$filename][$rst[$k]['name']]['status'] != 2) {
                                $file_info[$offset][$filename][$rst[$k]['name']] = [
                                    'href' => $viewpath . $rst[$k]['savepath'] . $rst[$k]['savename'],
                                    'status' => 3
                                ];
                            } else {
                                $file_info[$offset][$filename][$rst[$k]['name']] = [
                                    'href' => $viewpath . $rst[$k]['savepath'] . $rst[$k]['savename'],
                                    'status' => 2
                                ];
                            }
                        } else {
                            $file_info[$offset][$filename][$rst[$k]['name']] = [
                                'href' => $viewpath . $rst[$k]['savepath'] . $rst[$k]['savename'],
                                'status' => 2
                            ];
                        }
                    }
                    $this->redis->hset('file_'.$this->uuid,$menu,serialize($file_info));
                }
            }
        }
    }
    
    /**
     * 生成新数据
     * @param array $data post数据
     * @param array $item 子集数据结构
     * @return array 返回生成新值子集数组
     */
    private function createNewData($data,$item){
        foreach($item as $k => $v){
            if(array_key_exists($k,$data)){
                if($v['type'] == 'DATE' && $data[$k] != ''){
                    $data[$k] = $data[$k].' 00:00:00.0';
                }
                $item[$k]['value'] = $data[$k];
                $item[$k]['oldvalue'] = '';
            }
        }
        return $item;
    }
    
    /**
     * 添加新数据
     */
    public function addInfo(){
        $data = I('get.');
        if(!$menu = $data['menu']){
            $this -> error('非法参数传递!');
        }
        $userinfo = $this->sub_list;
        $list = $userinfo[$menu]['sublist'];
        $list_keys = array_keys($list);
        //1.生成字典文件
        A('Pc/Common') -> createDic();

        //2.检测是否存在主配置文件
        if(file_exists($this->main_conf_file)){
            $conf = unserialize(file_get_contents($this->main_conf_file));
            $conf = $conf[$menu];
            //dump($conf);exit;
            //0.过滤标准
            $filterlist = $conf['sublist'];

            $sublist_buf = [];
            //过滤子集显示项 + 排序操作
            foreach($filterlist as $k => $v){
                if(in_array($v,$list_keys)){
                    $sublist_buf[$v] = $list[$v];
                }
            }
            $list = $sublist_buf;
        }
        //获取扩展配置文件
        $kz_info = json_decode(file_get_contents($this->kz_conf_file),true);
        $kz_info = $kz_info[$menu];
        //dump($kz_info);exit;

        //.获取时间验证字段
        $sj_info = json_decode(file_get_contents($this->sj_conf_file),true);
        $sj_info = $sj_info[$menu];
        //dump($this -> layer);exit;
        $this -> assign([
            'uuid'    => $this->uuid,
            'menu'    => $menu,
            'sublist' => json_encode($list),
            'dic'     => $this -> dic,
            'layer'   => $this -> layer,
            'kz_info' => json_encode($kz_info),
            'sj_info' => json_encode($sj_info),
        ]);
        $this -> display('add');
    }
    
    /**
     * 截取caption长度为8个汉字长度
     */
    private function cut_caption($dat){
        $list = $dat['sublist'];
        foreach($list as $k => $v){
            if(mb_strlen($v['caption'],'utf-8')>7){
                $list[$k]['caption'] = mb_substr($v['caption'],0,7,'utf-8').'..';
            }
        }
        $dat['sublist'] = $list;
        return $dat;
    }
    
    /**
     * 执行添加新数据
     */
    public function addok(){
        $data = I('post.');
        //dump($data);exit;
        $table_name = $data['table_name'];
        $userinfo = $this->sub_list;
        $temp_data = $userinfo[$table_name];

        $res = $this -> createNewData($data,$temp_data['sublist']);
        $info = $this -> info;
        $setlist = [
            'awsid' => '',
            'info' => $res,
            'change_type' => 1
        ];

        $info['information'][$table_name]['subvalue'][] = $setlist;
        $keys = array_keys($info['information'][$table_name]['subvalue']);
        $newkey = max($keys);
        //dump($maxkey);exit;
        $info['information'][$table_name]['status'] = $temp_data['status'];
        $info['information'][$table_name]['status']['insert'][] = $newkey;
        $info['information'][$table_name]['change_type'] = 1;

        //上传附件
        $file = $_FILES;
        foreach($_FILES as $k=>$v){
            $tob = 0;
            foreach($v['name'] as $k1=>$v1){
                if($v1){
                    $tob++;
                }
            }
            if($tob){
                $this->upload($k,$data['table_name'],$newkey);
                $_FILES = $file;
            }
        }
        //获取唯一性字段
        $wyx_info = [];
        foreach($temp_data['sublist'] as $k=>$v){
            if($v['wyx'] == true){
                $wyx_info[] = $k;
            }
        }
        //整理唯一性字段数据
        if($wyx_info){
            foreach($wyx_info as $k=>$v){
                if($data[$v] == '是'){
                    if(isset($data['upd-'.$v])){
                        $val = $data['upd-'.$v];
                        $info['information'][$table_name]['subvalue'][$val]['info'][$v]['oldvalue'] = $info['information'][$table_name]['subvalue'][$val]['info'][$v]['value'];
                        $info['information'][$table_name]['subvalue'][$val]['info'][$v]['value'] = '否';
                        $info['information'][$table_name]['subvalue'][$val]['info'][$v]['change_type'] = 1;
                        $info['information'][$table_name]['subvalue'][$val]['change_type'] = 1;
                        if(!in_array($val,$info['information'][$table_name]['status']['insert'])){
                            //索引为已有数据
                            $info['information'][$table_name]['status']['update'][] = $val;
                            //去重处理
                            $info['information'][$table_name]['status']['update'] = array_unique($info['information'][$table_name]['status']['update']);
                        }
                    }
                }
            }
        }
        //dump($info['information'][$table_name]);exit;
        //数据回写
        $info = json_encode($info);
        //回写数据
        $this -> redis -> select(10);
        $this -> redis -> hset('user_list',$this->uuid,$info);
        $this -> success('添加成功!','/User/List/index/menu/'.$table_name);
    }
    
    /**
     * 删除子集数据
     */
    public function delInfo(){
        //收集所需数据
        $data = I('get.');
        $tablename = $data['tablename'];
        $_offset_id = $data['id'];

        $info = $this -> info;
        $sub_list = $info['information'];
        $temp_list = $sub_list[$tablename];
        //dump($temp_list);exit;

        //分析更改状态
        $status = $temp_list['status'];
        //1.新增数据情况 直接删除该新增状态
        $inter_offset = array_search($_offset_id,$status['insert']);
        if($inter_offset !== false){
            unset($status['insert'][$inter_offset]);
            $status['insert'] = array_values($status['insert']);
            //移除数据
            unset($temp_list['subvalue'][$_offset_id]);
        }else {
            //已更改过的数据则删除在update里的数据
            $upd_offset = array_search($_offset_id, $status['update']);
            if ($upd_offset !== false) {
                unset($status['update'][$upd_offset]);
                $status['update'] = array_values($status['update']);
            }
            //2.把删除的数据的awsid写进delete,当前数据加上删除标识,不做物理删除
            $temp_list['subvalue'][$_offset_id]['no_display'] = true;
            $temp_list['subvalue'][$_offset_id]['change_type'] = 1;
            $awsid = $temp_list['subvalue'][$_offset_id]['awsid'];
            $status['delete'][$_offset_id] = $awsid;

            $temp_list['change_type'] = 1;
        }
        //去除审批标识
        unset($temp_list['subvalue'][$_offset_id]['sp_type']);
        unset($temp_list['subvalue'][$_offset_id]['reason']);

        $temp_list['status'] = $status;
        if(count($status['insert'])==0 && count($status['update'])==0 && count($status['delete'])==0){
            $temp_list['change_type'] = 0;
        }
        //dump($temp_list);exit;
        //回填数据
        $info = $this -> info;
        $info['information'][$tablename] = $temp_list;
        //dump($info);exit;
        $info = json_encode($info);
        //回写数据
        $this -> redis -> select(10);
        $this -> redis -> hset('user_list',$this->uuid,$info);
        $this -> success('删除成功!','/User/List/index/menu/'.$tablename);
    }

    //验证字段唯一性
    public  function checkWyx(){
        $data = I('post.');
        $uuid = $data['uuid'];
        $item = $data['item'];
        $name = $data['name'];
        $offset = $data['offset'];
//        $uuid = '5098019738';
//        $item = 'BO_CASC_HR_XLJXWXX';
//        $name = 'SFZGXL';
        //获取当前uuid当前子集
        $userinfo = json_decode($this->redis->hget('user_list',$uuid),true);
        $userlist = $userinfo['information'][$item];
        //查看当前字段的值
        $subvalue = $userlist['subvalue'];
        if(count($subvalue) == 0){
            $resolt['type'] = 1;
        }else{
            $arr = '';
            foreach($subvalue as $k=>$v){
                if($offset){
                    if($k != $offset && !$v['no_display'] && $v['info'][$name]['value'] == '是'){
                        $arr .= $k.',';
                    }
                }else{
                    if(!$v['no_display'] && $v['info'][$name]['value'] == '是'){
                        $arr .= $k.',';
                    }
                }
            }
            if(!$arr){
                $resolt['type'] = 1;
            }else{
                $resolt = [
                    'type' => 2,
                    'key' => rtrim($arr,',')
                ];
            }
        }
        //dump($resolt);exit;
        $this->ajaxReturn($resolt);
    }
}